package com.example.fengyungo_user.activity.main;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.example.fengyungo_user.R;
import com.example.fengyungo_user.activity.BaseActivity;
import com.example.fengyungo_user.constant.CodeConstant;
import com.example.fengyungo_user.constant.MapConstant;
import com.example.fengyungo_user.constant.OrderConstant;
import com.example.fengyungo_user.domain.OrderDetailsDTO;
import com.example.fengyungo_user.utils.CommonUtil;
import com.example.fengyungo_user.utils.OssUtils;
import com.example.fengyungo_user.utils.PermissionUtil;
import com.example.fengyungo_user.utils.UserUtils;

import java.util.Calendar;
import java.util.Locale;

/**
 * @author 徐
 */
public class AddOrderActivity extends BaseActivity {
    private static final String TAG = "AddOrderActivity";
    /**
     * 起点
     */
    private String beginPosition;
    /**
     * 终点
     */
    private String endPosition;
    /**
     * 距离
     */
    private String distance;
    /**
     * 用户id
     */
    private String userId;
    /**
     * 最早接收日期
     */
    private String earliestDate;
    /**
     * 最早接收时间
     */
    private String earliestTime;
    /**
     * 最晚送达日期
     */
    private String latestDate;
    /**
     * 最晚送达时间
     */
    private String latestTime;
    /**
     * 长
     */
    private String length;
    /**
     * 宽
     */
    private String width;
    /**
     * 高
     */
    private String height;
    /**
     * 重
     */
    private String weight;
    /**
     * 长EditText
     */
    private EditText lengthEt;
    /**
     * 宽EditText
     */
    private EditText widthEt;
    /**
     * 高EditText
     */
    private EditText heightEt;
    /**
     * 重EditText
     */
    private EditText weightEt;
    /**
     * 备注EditText
     */
    private EditText noteEt;
    /**
     * 物品图片
     */
    private ImageView image;
    /**
     * 最早接收日期
     */
    private TextView earliestDateTv;
    /**
     * 最早接收时间
     */
    private TextView earliestTimeTv;
    /**
     * 最晚送达日期
     */
    private TextView latestDateTv;
    /**
     * 最晚送达时间
     */
    private TextView latestTimeTv;
    /**
     * Context
     */
    private Context context;
    /**
     * 日期选择的年份
     */
    private int year;
    /**
     * 日期选择的月
     */
    private int monthOfYear;
    /**
     * 日期选择的日
     */
    private int dayOfMonth;
    /**
     * 日期选择弹框
     */
    private DatePickerDialog datePickerDialog;
    /**
     * 点击事件监听器
     */
    private View.OnClickListener onClickListener;
    /**
     * Calendar
     */
    private Calendar calendar;
    /**
     * 时间选择
     */
    private TimePickerDialog timePickerDialog;
    /**
     * 选择的图片的路径
     */
    private String picturePath;
    /**
     * 确定
     */
    private Button ok;
    /**
     * 备注String
     */
    private String note;
    /**
     * 价格
     */
    private Double price;
    /**
     * 长
     */
    private Double doubleLength;
    /**
     * 宽
     */
    private Double doubleWidth;
    /**
     * 高
     */
    private Double doubleHeight;
    /**
     * 重
     */
    private Double doubleWeight;
    /**
     * 距离
     */
    private Double doubleDistance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_order);

        calendar = Calendar.getInstance();
        // 获取起点、终点、距离
        getIntentFrom();
        // 获取用户id
        userId = UserUtils.getUserInfo(this).getUserId();

        // 初始化控件
        initControls();
        // 初始化日期选择弹窗
        initDatePickerDialog();
        // 设置事件监听
        setListener();

        earliestDateTv.setOnClickListener(onClickListener);
        earliestTimeTv.setOnClickListener(onClickListener);
        latestDateTv.setOnClickListener(onClickListener);
        latestTimeTv.setOnClickListener(onClickListener);
        image.setOnClickListener(onClickListener);
        ok.setOnClickListener(onClickListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CodeConstant.SELECT_PHOTO) {
            if (resultCode == RESULT_OK && data != null) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);

                // 刷新，设置图片
                Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
                // 设置图片
                image.setImageDrawable(drawable);
            }
        }
    }

    /**
     * 设置点击事件
     */
    private void setListener() {
        onClickListener = view -> {
            switch (view.getId()) {
                case R.id.tv_earliest_date:
                    // 弹出对话框
                    datePickerDialog.show();
                    // 确认按钮
                    datePickerDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener((v) -> {
                        // 获取选择的日期
                        earliestDate = getSelectedDate();
                        earliestDateTv.setText(earliestDate);
                        datePickerDialog.dismiss();
                    });
                    break;
                case R.id.tv_earliest_time:
                    timePickerDialog = new TimePickerDialog(
                            this,
                            (timePicker, hour, minute) -> {
                                earliestTime = CommonUtil.formatTime(hour, minute);
                                earliestTimeTv.setText(earliestTime);
                            },
                            calendar.get(Calendar.HOUR_OF_DAY),
                            calendar.get(Calendar.MINUTE),
                            true
                    );
                    timePickerDialog.show();
                    break;
                case R.id.tv_latest_date:
                    // 弹出对话框
                    datePickerDialog.show();
                    // 确认按钮
                    datePickerDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener((v) -> {
                        // 获取选择的日期
                        latestDate = getSelectedDate();
                        latestDateTv.setText(latestDate);
                        datePickerDialog.dismiss();
                    });
                    break;
                case R.id.tv_latest_time:
                    timePickerDialog = new TimePickerDialog(
                            this,
                            (timePicker, hour, minute) -> {
                                latestTime = CommonUtil.formatTime(hour, minute);
                                latestTimeTv.setText(latestTime);
                            },
                            calendar.get(Calendar.HOUR_OF_DAY),
                            calendar.get(Calendar.MINUTE),
                            true
                    );
                    timePickerDialog.show();
                    break;
                case R.id.image:
                    openAlbum();
                    break;
                case R.id.btn_ok:
                    // 检查是否选了图片
                    if (picturePath == null) {
                        Toast.makeText(context, OrderConstant.PLEASE_ADD_IMAGE_OF_THING, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 获取物品属性
                    length = lengthEt.getText().toString();
                    width = widthEt.getText().toString();
                    height = heightEt.getText().toString();
                    weight = weightEt.getText().toString();
                    note = noteEt.getText().toString();

                    // 检查日期有没有填
                    if (earliestTime == null || earliestDate == null || latestTime == null ||
                    latestDate == null) {
                        Toast.makeText(context, OrderConstant.PLEASE_FINISH_DATE, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    // 检查是否有属性未填
                    if ("".equals(length) || "".equals(width) || "".equals(height) || "".equals(weight)) {
                        Toast.makeText(context, OrderConstant.PLEASE_FINISH_THING_INFO, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 获取double属性
                    getDoubleAttributes();

                    // TODO: 2024/2/5 计算价格
                    price = doubleLength * doubleWidth * doubleHeight * 1 / 100 +
                            doubleWeight / 1000 + doubleDistance / 10000;
                    // 保留2位小数
                    String str = String.format(Locale.getDefault(), "%.2f", price);
                    price = Double.parseDouble(str);

                    // 上传图片
                    Log.d(TAG, "setListener: upload");
                    OssUtils.upload(this, OssUtils.getFilename(this, picturePath), picturePath);

                    // 跳转到支付页面
                    intentToPay();

                    break;
                default:
                    break;
            }
        };
    }

    /**
     * 获取double属性
     */
    private void getDoubleAttributes() {
        doubleLength = Double.parseDouble(length);
        doubleWidth = Double.parseDouble(width);
        doubleHeight = Double.parseDouble(height);
        doubleWeight = Double.parseDouble(weight);
        doubleDistance = Double.parseDouble(distance.substring(0, distance.lastIndexOf('m')));
    }

    /**
     * 跳转到支付页面
     */
    private void intentToPay() {
        Intent intent = new Intent(this, PayActivity.class);
        OrderDetailsDTO orderDetailsDTO = new OrderDetailsDTO();
        orderDetailsDTO.setUserId(userId);
        orderDetailsDTO.setBegin(beginPosition);
        orderDetailsDTO.setEnd(endPosition);
        orderDetailsDTO.setEarliestTime(earliestDate + " " + earliestTime);
        orderDetailsDTO.setLatestTime(latestDate + " " + latestTime);
        orderDetailsDTO.setNote(note);
        orderDetailsDTO.setPrice(price);
        orderDetailsDTO.setLength(doubleLength);
        orderDetailsDTO.setWidth(doubleWidth);
        orderDetailsDTO.setHeight(doubleHeight);
        orderDetailsDTO.setWeight(doubleWeight);
        orderDetailsDTO.setImage(OssUtils.generateOssUrl(this, picturePath));
        intent.putExtra(OrderConstant.ORDER_DETAILS_DTO, orderDetailsDTO);
        startActivity(intent);
    }

    /**
     * 获取选择的日期
     */
    private String getSelectedDate() {
        year = datePickerDialog.getDatePicker().getYear();
        monthOfYear = datePickerDialog.getDatePicker().getMonth() + 1;
        dayOfMonth = datePickerDialog.getDatePicker().getDayOfMonth();
        return CommonUtil.formatDate(year, monthOfYear, dayOfMonth);
    }

    /**
     * 初始化日期选择弹框
     */
    private void initDatePickerDialog() {
        datePickerDialog = new DatePickerDialog(context, null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * 初始化控件
     */
    private void initControls() {
        context = this;
        lengthEt = findViewById(R.id.et_length);
        widthEt = findViewById(R.id.et_width);
        heightEt = findViewById(R.id.et_height);
        weightEt = findViewById(R.id.et_weight);
        noteEt = findViewById(R.id.et_note);
        image = findViewById(R.id.image);
        earliestDateTv = findViewById(R.id.tv_earliest_date);
        earliestTimeTv = findViewById(R.id.tv_earliest_time);
        latestDateTv = findViewById(R.id.tv_latest_date);
        latestTimeTv = findViewById(R.id.tv_latest_time);
        ok = findViewById(R.id.btn_ok);
    }

    /**
     * 获取起点、终点信息从intent
     */
    private void getIntentFrom() {
        Intent intent = getIntent();
        // 起点
        beginPosition = intent.getStringExtra(MapConstant.BEGIN_ADDRESS);
        // 终点
        endPosition = intent.getStringExtra(MapConstant.END_ADDRESS);
        // 距离：例如100m
        distance = intent.getStringExtra(MapConstant.DISTANCE);

        Toast.makeText(this, "起点：" + beginPosition, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "终点：" + endPosition, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "距离：" + distance, Toast.LENGTH_SHORT).show();
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 动态获取权限
            PermissionUtil.getPermission(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
            return;
        }
        //Intent.ACTION_PICK 从数据中选择一个项目 (item)，将被选中的项目返回。
        //MediaStore.Images.Media.EXTERNAL_CONTENT_URI 获取外部的URI
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        //参数一:对应的数据的URI 参数二:使用该函数表示要查找文件的MIME类型
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, CodeConstant.SELECT_PHOTO);
    }
}